package com.vf.admin.client.controller.pay.sandpay.weixin;

import com.vf.admin.client.result.PayInfoResult;
import com.vf.admin.client.service.AppOrderService;
import com.vf.admin.client.service.VipOrderService;
import com.vf.admin.common.Constants;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.pay.ApiAplayWeChat.IpUtils;
import com.vf.admin.client.controller.pay.sandpay.util.RSAUtil;
import com.vf.admin.client.controller.pay.sandpay.util.ShanDeConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.vf.admin.utils.RandomUtil.getOrderIdByUUId;

/**
 * <p>Title : 杉德微信支付</p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows10</p>
 *
 * @Author : NemoMeng
 * @Date 2023/7/3 11:54
 */
@Service
public class SandWeiXinPayService {

    //钱包订单
    @Autowired
    private AppOrderService appOrderService;
    //vip订单
    @Autowired
    private VipOrderService vipOrderService;

    /**
     * 钱包
     *
     * @param request
     * @param user
     * @param czMoney
     * @return
     */
    public PayInfoResult diamondRechargeH5(HttpServletRequest request, AppUser user, AppCzMoney czMoney,String mobileSpec) {

        //添加订单记录
        AppOrder appOrder = new AppOrder();
        appOrder.setCreatetime(new Date());
        appOrder.setOrdernum(getOrderIdByUUId());//生成订单号
        appOrder.setCzMoneyId(czMoney.getId());
        appOrder.setMoney(new BigDecimal(czMoney.getMoney()));
        appOrder.setStatus(Constants.dingdan_status_dfk);//默认 1、代付款 2、已付款
        appOrder.setType(Constants.dingdan_zhiFuLeiXing_shande_wx); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        appOrder.setUserid(user.getId());//下单人信息
        appOrder.setPic(user.getPic());
        appOrder.setNick(user.getNick());
        appOrder.setPhone(user.getLoginname());
        appOrder.setMobileSpec(mobileSpec);
        appOrder.setNum(czMoney.getDiamonds().add(czMoney.getGive()));
        appOrderService.save(appOrder);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        String createTime = sdf.format(calendar.getTime());
        calendar.add(Calendar.HOUR, 1);
        String endTime = sdf.format(calendar.getTime());

        String version = "10";
        //商户号
        String mer_no = ShanDeConstants.mer_no;
        //订单号
        String mer_order_no = appOrder.getOrdernum();
        //回调地址
//        String notify_url = ShanDeConstants.wx_notify_url_dev;
        String notify_url = ShanDeConstants.wx_notify_url_prod;

        //金额
        String order_amt = new BigDecimal(czMoney.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
//        String order_amt = "0.01";
        //商品名称
        String goods_name = "钻石充值";
        //支付扩展域
        //云函数所需参数，resourceAppid：小程序AppID； resourceEnv：云开发环境 ID
//        String pay_extra = "{\"resourceAppid\":\"wxccc9523884c77fa9\",\"resourceEnv\":\"wxccc9523884c77fa9-7dp5ce0d12fd1\"}";
//        String pay_extra = "{\"resourceAppid\":\"wxccc9523884c77fa9\",\"resourceEnv\":\"zhiyu-4gxv9hea69092071\"}";
        String pay_extra = "{\"resourceAppid\":\"wxccc9523884c77fa9\",\"resourceEnv\":\"zhiyu-4go1k1iefb1d28fe\"}";

        String realIp = IpUtils.getRealIp(request);
        //商户私钥
        PrivateKey privateKey = RSAUtil.getPrivateKey();

        Map<String, String> map = new LinkedHashMap<>();
        map.put("accsplit_flag", "NO");
//        map.put("create_ip", "127_0_0_1");
        map.put("create_ip", realIp);
        map.put("create_time", createTime);

        map.put("mer_no", mer_no);
        map.put("mer_order_no", mer_order_no);
        map.put("notify_url", notify_url);
        map.put("order_amt", order_amt);
        map.put("pay_extra", pay_extra);
        map.put("return_url", "");
        map.put("sign_type", "RSA");
        map.put("store_id", "000000");
        map.put("version", version);

        //map.put("expire_time",endTime);
        //map.put("goods_name",goods_name);
        //map.put("product_code","02010006");
        //map.put("clear_cycle","0");


        String content = RSAUtil.getSignContent(map);
        System.out.println("参与签名字符串：\n" + content);

        String sign = RSAUtil.sign(content, privateKey);
        System.out.println("签名串：\n" + sign);

        //拼接url
        String url = null;

        String prod = "https://sandcash.mixienet.com.cn/pay/h5/applet?";
        String dev = "https://sandcash-uat01.sand.com.cn/pay/h5/applet?";

        try {
            url = prod +
                    //云函数h5： applet  ；支付宝H5：alipay  ； 微信公众号H5：wechatpay   ；
                    //一键快捷：fastpayment   ；H5快捷 ：unionpayh5    ；支付宝扫码：alipaycode ;快捷充值:quicktopup
                    //电子钱包【云账户】：cloud
                    "version=" + version + "" +
                    "&mer_no=" + mer_no + "" +
                    "&mer_order_no=" + mer_order_no + "" +
                    "&create_time=" + createTime + "" +
                    "&expire_time=" + endTime + "" +  //endTime
                    "&order_amt=" + order_amt + "" +
                    "&notify_url=" + URLEncoder.encode(notify_url, "UTF-8") + "" +
                    "&return_url=" +
                    "&create_ip=" + realIp + "" +
                    "&goods_name=" + URLEncoder.encode(goods_name, "UTF-8") + "" +
                    "&store_id=000000" +
                    //产品编码: 云函数h5：  02010006  ；支付宝H5：  02020002  ；微信公众号H5：02010002   ；
                    //一键快捷：  05030001  ；H5快捷：  06030001   ；支付宝扫码：  02020005 ；快捷充值：  06030003
                    //电子钱包【云账户】：开通账户并支付product_code应为：04010001；消费（C2C）product_code 为：04010003 ; 我的账户页面 product_code 为：00000001
                    "&product_code=02010006" + "" +
                    "&clear_cycle=3" +
                    "&pay_extra=" + URLEncoder.encode(pay_extra, "UTF-8") + "" +
                    "&meta_option=%5B%7B%22s%22%3A%22Android%22,%22n%22%3A%22wxDemo%22,%22id%22%3A%22com.pay.paytypetest%22,%22sc%22%3A%22com.pay.paytypetest%22%7D%5D" +
                    "&accsplit_flag=NO" +
                    "&jump_scheme=" +
                    "&sign_type=RSA" +
                    "&sign=" + URLEncoder.encode(sign, "UTF-8") + "";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //参数包装
        PayInfoResult payInfoResult = new PayInfoResult();
        payInfoResult.setOrderNo(mer_order_no);
        payInfoResult.setPayUrl(url);
        return payInfoResult;
    }


    /**
     * 会员
     *
     * @param request
     * @param user
     * @param vipPackage
     * @return
     */
    public PayInfoResult openVipRechargeH5(HttpServletRequest request, AppUser user, VipPackage vipPackage,String mobileSpec) {
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());//
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType("shande");
        vipOrder.setCreateTime(new Date());
        vipOrder.setType(Constants.dingdan_zhiFuLeiXing_shande_wx); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrder.setMobileSpec(mobileSpec);
        vipOrderService.save(vipOrder);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        String createTime = sdf.format(calendar.getTime());
        calendar.add(Calendar.HOUR, 1);
        String endTime = sdf.format(calendar.getTime());

        String version = "10";
        //商户号
        String mer_no = ShanDeConstants.mer_no;
        //订单号
        String mer_order_no = vipOrder.getOrderNo();
        //回调地址
//        String notify_url = ShanDeConstants.wx_notify_url_dev;
        String notify_url = ShanDeConstants.wx_notify_url_prod;
        //金额
        String order_amt = vipPackage.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
//        String order_amt = "0.01";
        //商品名称
        String goods_name = "会员充值";
        //支付扩展域
        //云函数所需参数，resourceAppid：小程序AppID； resourceEnv：云开发环境 ID
//        String pay_extra = "{\"resourceAppid\":\"wxccc9523884c77fa9\",\"resourceEnv\":\"wxccc9523884c77fa9-7dp5ce0d12fd1\"}";
//        String pay_extra = "{\"resourceAppid\":\"wxccc9523884c77fa9\",\"resourceEnv\":\"zhiyu-4gxv9hea69092071\"}";
        String pay_extra = "{\"resourceAppid\":\"wxccc9523884c77fa9\",\"resourceEnv\":\"zhiyu-4go1k1iefb1d28fe\"}";
        String realIp = IpUtils.getRealIp(request);
        //商户私钥
        PrivateKey privateKey = RSAUtil.getPrivateKey();

        Map<String, String> map = new LinkedHashMap<>();
        map.put("accsplit_flag", "NO");
//        map.put("create_ip", "127_0_0_1");
        map.put("create_ip", realIp);
        map.put("create_time", createTime);

        map.put("mer_no", mer_no);
        map.put("mer_order_no", mer_order_no);
        map.put("notify_url", notify_url);
        map.put("order_amt", order_amt);
        map.put("pay_extra", pay_extra);
        map.put("return_url", "");
        map.put("sign_type", "RSA");
        map.put("store_id", "000000");
        map.put("version", version);

        //map.put("expire_time",endTime);
        //map.put("goods_name",goods_name);
        //map.put("product_code","02010006");
        //map.put("clear_cycle"R,"0");


        String content = RSAUtil.getSignContent(map);
        System.out.println("参与签名字符串：\n" + content);

        String sign = RSAUtil.sign(content, privateKey);
        System.out.println("签名串：\n" + sign);

        //拼接url
        String url = null;
        String prod = "https://sandcash.mixienet.com.cn/pay/h5/applet?";
        String dev = "https://sandcash-uat01.sand.com.cn/pay/h5/applet?";

        try {
            url = prod +
                    //云函数h5： applet  ；支付宝H5：alipay  ； 微信公众号H5：wechatpay   ；
                    //一键快捷：fastpayment   ；H5快捷 ：unionpayh5    ；支付宝扫码：alipaycode ;快捷充值:quicktopup
                    //电子钱包【云账户】：cloud
                    "version=" + version + "" +
                    "&mer_no=" + mer_no + "" +
                    "&mer_order_no=" + mer_order_no + "" +
                    "&create_time=" + createTime + "" +
                    "&expire_time=" + endTime + "" +  //endTime
                    "&order_amt=" + order_amt + "" +
                    "&notify_url=" + URLEncoder.encode(notify_url, "UTF-8") + "" +
                    "&return_url=" +
                    "&create_ip=" + realIp + "" +
                    "&goods_name=" + URLEncoder.encode(goods_name, "UTF-8") + "" +
                    "&store_id=000000" +
                    //产品编码: 云函数h5：  02010006  ；支付宝H5：  02020002  ；微信公众号H5：02010002   ；
                    //一键快捷：  05030001  ；H5快捷：  06030001   ；支付宝扫码：  02020005 ；快捷充值：  06030003
                    //电子钱包【云账户】：开通账户并支付product_code应为：04010001；消费（C2C）product_code 为：04010003 ; 我的账户页面 product_code 为：00000001
                    "&product_code=02010006" + "" +
                    "&clear_cycle=3" +
                    "&pay_extra=" + URLEncoder.encode(pay_extra, "UTF-8") + "" +
                    "&meta_option=%5B%7B%22s%22%3A%22Android%22,%22n%22%3A%22wxDemo%22,%22id%22%3A%22com.pay.paytypetest%22,%22sc%22%3A%22com.pay.paytypetest%22%7D%5D" +
                    "&accsplit_flag=NO" +
                    "&jump_scheme=" +
                    "&sign_type=RSA" +
                    "&sign=" + URLEncoder.encode(sign, "UTF-8") + "";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //参数包装
        PayInfoResult payInfoResult = new PayInfoResult();
        payInfoResult.setOrderNo(mer_order_no);
        payInfoResult.setPayUrl(url);
        return payInfoResult;
    }


}
